package com.itlong.cloud.controller.sdkV3.elevator;

import com.alibaba.fastjson.JSONObject;
import com.itlong.cloud.POJO.DTO.app.AppCallLiftSaveDTO;
import com.itlong.cloud.POJO.DTO.sdk.CloudDeviceSDKDTO;
import com.itlong.cloud.POJO.DTO.sdk.CloudElevatorSDKGetByDeviceUniqueDTO;
import com.itlong.cloud.POJO.DTO.sdk.CloudElevatorSDKServerElevatorKeyDTO;
import com.itlong.cloud.POJO.DTO.sdk.v3.*;
import com.itlong.cloud.POJO.PO.DeviceElevatorInfoPO;
import com.itlong.cloud.POJO.VO.SDKMessageV3;
import com.itlong.cloud.POJO.VO.property.CloudElevatorVO;
import com.itlong.cloud.POJO.VO.sdk.v3.hw.*;
import com.itlong.cloud.annotation.LoggerInfo;
import com.itlong.cloud.annotation.UnAuthAccessRequired;
import com.itlong.cloud.constants.*;
import com.itlong.cloud.enumerate.CallElevatorRecordSourceEnum;
import com.itlong.cloud.enumerate.IotDeviceStatusEnum;
import com.itlong.cloud.enumerate.ecode.*;
import com.itlong.cloud.equip.app.IAppDeviceServiceClient;
import com.itlong.cloud.equip.sdk.ICloudElevatorSDKRobotClient;
import com.itlong.cloud.equip.sdk.ICloudElevatorSDKServerCloudServiceClient;
import com.itlong.cloud.equip.sdkv3.ISDKV3EquipClient;
import com.itlong.cloud.iottp.IIotServerServiceClient;
import com.itlong.cloud.iottp.ISDKV3Client;
import com.itlong.cloud.project.operate.IOperateProjectServiceClient;
import com.itlong.cloud.sdkv3.service.ITaskService;
import com.itlong.cloud.service.RedisService;
import com.itlong.cloud.service.sdkv3.ICheckService;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.user.app.IAppHomeServiceClient;
import com.itlong.cloud.user.sdk.ICloudTalkSDKServerUserServiceClient;
import com.itlong.cloud.utils.date.DateUtil;
import com.itlong.cloud.utils.network.http.HttpProtocolUtil;
import com.itlong.cloud.utils.tool.DeviceUtil;
import com.itlong.cloud.utils.tool.MathUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <desc>
 * 云电梯SDKV3
 * </desc>
 *
 * @createDate 2021-05-14
 */
@RestController
@RequestMapping("/sdkv3/cloud/elevator")
public class ElevatorController {

    private static final Logger LOG = LoggerFactory.getLogger(ElevatorController.class);

    @Autowired
    ICloudElevatorSDKRobotClient iCloudElevatorSDKRobotServiceClient;

    @Autowired
    ICloudElevatorSDKServerCloudServiceClient iCloudElevatorSDKServerCloudServiceClient;

    @Autowired
    IAppDeviceServiceClient iAppDeviceServiceClient;

    @Autowired
    ISDKV3Client iSDKV3Client;

    @Autowired
    ISDKV3EquipClient iSDKV3EquipClient;

    @Autowired
    ICloudTalkSDKServerUserServiceClient iCloudTalkSDKServerUserServiceClient;

    @Autowired
    IAppHomeServiceClient iAppHomeServiceClient;

    @Autowired
    IIotServerServiceClient iIotServerServiceClient;

    @Autowired
    IOperateProjectServiceClient iOperateProjectServiceClient;

    @Autowired
    RedisService redisService;

    @Autowired
    ITaskService iTaskService;

    @Autowired
    ICheckService iCheckService;

    /**
     * <desc>
     * 预约乘梯
     * <desc/>
     *
     * @return
     * @author zhouchun
     * @createDate 2021-05-14
     */
    @RequestMapping(path = "/callElevator", method = RequestMethod.POST)
    @LoggerInfo(operateDesc = LogDescConstant.SDK_ROBOT_CALL_ELEVATOR)
    @ResponseBody
    public Object callElevator(HttpServletRequest request) {
        try {
            //收到请求的时间
            long requestTime = DateUtil.getTimestamp();
            CallElevatorDTO callElevatorDTO = HttpProtocolUtil.parseRequestParamToDTO(CallElevatorDTO.class, request);
            CallElevatorRespDTO callElevatorRespDTO = new CallElevatorRespDTO();
            BeanUtils.copyProperties(callElevatorDTO, callElevatorRespDTO);
            String requestId = callElevatorDTO.getRequestId();
            String robotId = callElevatorDTO.getRobotId();
            String deviceUnique = callElevatorDTO.getDeviceUnique();
            String fromFloor = callElevatorDTO.getFromFloor();
            String toFloor = callElevatorDTO.getToFloor();
            String openTime = callElevatorDTO.getOpenTime();
            String projectId = callElevatorDTO.getProjectId();
            //打印入参
            LOG.info("【SDKV3 callElevator 入参】{}", callElevatorDTO);
            //参数校验
            if (deviceUnique == null || deviceUnique.equals("")) {
                return new SDKMessageV3(SDKV3ErrorCodeEnum.NO_DEVICE_UNIQUE_ERROR.getErrorCode(), requestId);
            }
            //deviceUnique格式不对
            if (!DeviceUtil.isDeviceUnique(deviceUnique)) {
                return new SDKMessageV3(SDKV3ErrorCodeEnum.DEVICE_UNIQUE_ERROR.getErrorCode(), requestId);
            }
            if (fromFloor == null || fromFloor.equals("")) {
                return new SDKMessageV3(SDKV3ErrorCodeEnum.NO_FROM_FLOOR_ERROR.getErrorCode(), requestId);
            }
            if (toFloor == null || toFloor.equals("")) {
                return new SDKMessageV3(SDKV3ErrorCodeEnum.NO_TO_FLOOR_ERROR.getErrorCode(), requestId);
            }
            if (openTime == null || openTime.equals("")) {
                return new SDKMessageV3(SDKV3ErrorCodeEnum.NO_OPEN_TIME_ERROR.getErrorCode(), requestId);
            }
            if (!MathUtil.isInteger(openTime, 1, 99)) {
                return new SDKMessageV3(SDKV3ErrorCodeEnum.DOOR_OPEN_TIME_ERROR.getErrorCode(), requestId);
            }
            if (projectId == null || projectId.equals("")) {
                return new SDKMessageV3(SDKV3ErrorCodeEnum.PROJECT_ID_NOT_SET.getErrorCode(), requestId);
            }
            //数据设置
            boolean isYQK = DeviceUtil.isYQK(deviceUnique);
            callElevatorDTO.setSnr(requestId + "-" + deviceUnique);
            callElevatorDTO.setAppId(request.getAttribute("appId").toString());
            callElevatorDTO.setAppSecret(request.getAttribute("appSecret").toString());
            callElevatorDTO.setRobotDevelopDeviceType(RobotDevelopDeviceTypeConstant.YDT);
            callElevatorDTO.setDeviceType(SolutionTypeConstant.STRING_ELEVATOR_ROBOT_CLOUD);
            //
            SDKMessageV3 response = iCheckService.check1(requestId, callElevatorDTO.getAppId(), callElevatorDTO.getRoleId());
            if (response.getMsgCode() != 0) {
                return response;
            }
            //
            Map<String, Object> AuthStatus = iOperateProjectServiceClient.getRobotGoProjectWhitelistAndDeviceAuthStatusByUserId(callElevatorDTO.getProjectId(), callElevatorDTO.getAppId());
            response = iCheckService.check2(requestId, requestTime, AuthStatus);
            if (response.getMsgCode() != 0) {
                return response;
            }
            if (isYQK) {
                if (AuthStatus.get("robotNoninductive").toString().equals("0")) {
                    return new SDKMessageV3(SDKV3ErrorCodeEnum.AUTH_YQK_ERROR.getErrorCode(), requestId);
                }
            } else {
                if (AuthStatus.get("robotToCloud").toString().equals("0")) {
                    return new SDKMessageV3(SDKV3ErrorCodeEnum.AUTH_YDT_ERROR.getErrorCode(), requestId);
                }
            }
            callElevatorDTO.setRobotWhiteListAuthStatus(Integer.parseInt(AuthStatus.get("robotWhiteListAuthStatus") + ""));
            callElevatorDTO.setRobotDeviceAuthStatus(Integer.parseInt(AuthStatus.get("robotDeviceAuthStatus") + ""));
            String deviceUniqueList = "";
            if (isYQK) {
                callElevatorDTO.setRobotDevelopDeviceType(RobotDevelopDeviceTypeConstant.YQK);
                callElevatorDTO.setDeviceType(SolutionTypeConstant.STRING_ELEVATOR_ROBOT_YQK);
                //群控器是否在线
                String state = redisService.get(RedisConstant.DEVICE_CLUSTER_IS_ONLINE_KEY + deviceUnique);
                if (state == null || !state.equals("1")) {
                    return new SDKMessageV3(SDKV3ErrorCodeEnum.YQK_ONLINE_ERROR.getErrorCode(), requestId);
                }
                //群控器是否有绑定电梯
                deviceUniqueList = iCloudElevatorSDKServerCloudServiceClient.getDeviceUniqueByControllerDeviceUnique(deviceUnique);
                if (StringUtils.isBlank(deviceUniqueList)) {
                    return new SDKMessageV3(CloudElevarotErrorCodeEnum.CONTROLLER_NOT_FOUND.getErrorCode(), requestId);
                }
            }
            //保存生成操作日志所需信息
            request.setAttribute("remark", callElevatorDTO.toString());
            request.setAttribute("portType", LogDescConstant.SDK_CLOUD_ELEVATOR_TYPE_LOG_DESC);
            //设备权限以及机器人权限验证
            CloudDeviceSDKDTO t = new CloudDeviceSDKDTO();
            BeanUtils.copyProperties(callElevatorDTO, t);
            t.setFlag(callElevatorDTO.getRobotDevelopDeviceType());
            int result = this.checkDeveloperAuth(t);
            if (result == 1) {
                return new SDKMessageV3(SDKErrorCodeEnum.SDK_SERVER_NO_DEVICE_UNIQUE_ERR.getErrorCode(), requestId);
            } else if (result == 2) {
                return new SDKMessageV3(CloudElevarotErrorCodeEnum.ROBOT_AUTH_ERROR.getErrorCode(), requestId);
            }
            //云电梯设备判断,标准版不支持机器人功能
            DeviceElevatorInfoPO po = iCloudElevatorSDKServerCloudServiceClient.getElevatorByDeviceUnique(deviceUnique);
            //设备属性配置 1标准 2云机器人 3全功能
            if (po != null && po.getDeviceAttributes() != null && po.getDeviceAttributes() == 1) {
                return new SDKMessageV3(SDKErrorCodeEnum.SDK_DEVICE_NOT_SUPPORT_THIS_FUNCTIONS.getErrorCode(), requestId);
            }
            //获取真实楼层
            Map<String, Object> floor;
            if (isYQK) {
                String[] temp = deviceUniqueList.split(",");
                floor = iCloudElevatorSDKServerCloudServiceClient.getFloorNumByLogicFloor(callElevatorDTO.getToFloor(), callElevatorDTO.getFromFloor(), temp[0]);
            } else {
                floor = iCloudElevatorSDKServerCloudServiceClient.getFloorNumByLogicFloor(callElevatorDTO.getToFloor(), callElevatorDTO.getFromFloor(), deviceUnique);
            }
            /*
                fromFloor=device_elevator_floor_config.floor_num(实际楼层)
                goFloor=device_elevator_floor_config.floor_num(实际楼层)
                fromNaturalFloor=device_elevator_floor_config.natural_floor(权限标识)
                goNaturalFloor=device_elevator_floor_config.natural_floor(权限标识)
            */
            if (floor == null || floor.get("goFloor") == null || floor.get("fromFloor") == null) {
                return new SDKMessageV3(CloudElevarotErrorCodeEnum.CLOUD_FLOOR_ERROR.getErrorCode(), requestId);
            }
            CloudElevatorVO vo = iAppDeviceServiceClient.getCallElevatorInfo(deviceUnique);
            if (!isYQK) {
                //判断当前设备是否在线，如不在线返回失败
                String isOnline = iIotServerServiceClient.batchGetDeviceState(vo.getIotProductKey(), deviceUnique);
                //判断设备是否在线
                if (isOnline == null || (isOnline != null && !isOnline.equals(IotDeviceStatusEnum.ONLINE.getType()))) {
                    return new SDKMessageV3(AppErrorCodeEnum.CLOUD_ELEVATOR_OUT_LINE.getErrorCode(), requestId);
                }
            }
            //检查参数
            ElevatorCheckDTO elevatorCheckDTO = new ElevatorCheckDTO();
            elevatorCheckDTO.setRequestId(requestId);
            elevatorCheckDTO.setRobotId(robotId);
            elevatorCheckDTO.setDeviceUnique(deviceUnique);
            elevatorCheckDTO.setStartingLogicalFloor(callElevatorDTO.getFromFloor());
            elevatorCheckDTO.setGotoLogicalFloor(callElevatorDTO.getToFloor());
            elevatorCheckDTO.setStartingNumFloor(floor.get("fromFloor").toString());
            elevatorCheckDTO.setGotoNumFloor(floor.get("goFloor").toString());
            elevatorCheckDTO.setFromNaturalFloor(floor.get("fromNaturalFloor").toString());
            elevatorCheckDTO.setToNaturalFloor(floor.get("goNaturalFloor").toString());
            elevatorCheckDTO.setUserId(callElevatorDTO.getAppId());
            response = iSDKV3EquipClient.cloudElevatorCheck(elevatorCheckDTO);
            //有错误
            if (response.getMsgCode() != 0) {
                return response;
            }
            /*
                deviceId
                startingFloor
                gotoFloor
                isVip
            */
            HashMap<String, String> map = (HashMap<String, String>) response.getData();
            //当前电梯已有乘梯任务
            if (iTaskService.hasElevatorKey(deviceUnique)) {
                Map<Object, Object> elevatorData = iTaskService.getElevatorData(deviceUnique);
                if (elevatorData != null && elevatorData.get("robotId") != null && elevatorData.get("robotId").toString().equals(robotId)) {
                    return new SDKMessageV3(SDKV3ErrorCodeEnum.ELEVATOR_HAS_TASK.getErrorCode(), requestId, callElevatorRespDTO);
                }
                return new SDKMessageV3(SDKV3ErrorCodeEnum.ELEVATOR_HAS_OTHER_TASK.getErrorCode(), requestId);
            }
            //上锁，指令提交的超时时间为5秒
            if (iTaskService.checkElevator(deviceUnique, 1L, 6000L)) {
                return new SDKMessageV3(SDKV3ErrorCodeEnum.ELEVATOR_HAS_ROBOT.getErrorCode(), requestId);
            }
            //调用IOT呼梯
            SetTravelCustomData setTravelCustomData = new SetTravelCustomData();
            setTravelCustomData.setSenderType("1");
            setTravelCustomData.setRobotId(callElevatorDTO.getRobotId());
            setTravelCustomData.setDoorOpenTime(callElevatorDTO.getOpenTime());
            setTravelCustomData.setStartingFloorCallMode(null);//不需要
            setTravelCustomData.setFloor(null);//不需要
            setTravelCustomData.setTime(null);//不需要
            setTravelCustomData.setIsVip(null);//不需要
            //
            SetTravelParas setTravelParas = new SetTravelParas();
            setTravelParas.setCmd("1023");
            setTravelParas.setCmdVer("0");
            setTravelParas.setSnr(requestId + "-" + deviceUnique);
            setTravelParas.setSourceFrom("itlong");
            setTravelParas.setStartingFloor(map.get("startingFloor"));
            setTravelParas.setGotoFloor(map.get("gotoFloor"));
            setTravelParas.setCustomData(JSONObject.toJSONString(setTravelCustomData));
            setTravelParas.setTimestamp(DateUtil.getTimestampString());
            setTravelParas.setUpDown("1");//下行
            if (Integer.valueOf(floor.get("fromFloor").toString()) <= Integer.valueOf(floor.get("goFloor").toString())) {
                setTravelParas.setUpDown("2");//上行
            }
            //
            SetTravel setTravel = new SetTravel();
            setTravel.setCommand_name("setTravel");
            setTravel.setParas(setTravelParas);
            setTravel.setService_id("SettingService");
            //乘梯指令下达(除了指令外还需要额外参数)
            SetTravelWrap setTravelWrap = new SetTravelWrap();
            setTravelWrap.setSetTravel(setTravel);
            setTravelWrap.setRequestId(requestId);
            setTravelWrap.setDeviceId(map.get("deviceId"));
            setTravelWrap.setRobotId(robotId);
            response = iSDKV3Client.cloudElevatorCall(setTravelWrap);
            if (response.getMsgCode() != 0) {
                //清除6秒的锁
                iTaskService.clearElevatorLockKey(deviceUnique);
                return response;
            }
            //再次判断锁
            if (iTaskService.checkElevator(deviceUnique, 2L, 0L)) {
                return new SDKMessageV3(SDKV3ErrorCodeEnum.ELEVATOR_HAS_ROBOT.getErrorCode(), requestId);
            }
            //电梯上锁
            iTaskService.setElevatorData(robotId, deviceUnique, isYQK);
            //设置任务
            callElevatorDTO.setIotDeviceId(map.get("deviceId"));//如果收不到派梯信息，通过内部的取消乘梯指令将任务取消掉
            iTaskService.setTaskData(callElevatorDTO);
            //清除6秒的锁
            iTaskService.clearElevatorLockKey(deviceUnique);
            //装配呼梯记录对象
            Thread thread = new Thread(new Runnable() {
                public void run() {
                    try {
                        AppCallLiftSaveDTO saveDTO = new AppCallLiftSaveDTO();
                        saveDTO.setDeviceUnique(deviceUnique);
                        saveDTO.setFromFloor(floor.get("fromNaturalFloor").toString());
                        saveDTO.setToFloor(floor.get("goNaturalFloor").toString());
                        saveDTO.setProjectId(callElevatorDTO.getProjectId());
                        saveDTO.setSource(CallElevatorRecordSourceEnum.ROBOT.getType());
                        saveDTO.setUserId(callElevatorDTO.getRobotId());
                        iAppHomeServiceClient.saveCallLiftRecord(saveDTO);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
            thread.start();
            return new SDKMessageV3(BaseErrorCodeEnum.SUCCESS.getErrorCode(), requestId, callElevatorRespDTO);
        } catch (Exception e) {
            request.setAttribute("exception", e.toString());
            throw new DataAccessException("【SDKV3_云电梯_callElevator】预约电梯异常", e);
        }
    }

    /**
     * <desc>
     * 开门关门
     * </desc>
     *
     * @return
     * @author zhouchun
     * @createDate 2021-05-18
     */
    @RequestMapping(path = "/sendOpenDoor", method = RequestMethod.POST)
    @LoggerInfo(operateDesc = LogDescConstant.SDK_SERVER_SEND_OPEN_CLOSE_DOOR_LOG_DESC)
    @ResponseBody
    public Object sendOpenDoor(HttpServletRequest request) {
        try {
            //收到请求的时间
            long requestTime = DateUtil.getTimestamp();
            OpenDoorDTO openDoorDTO = HttpProtocolUtil.parseRequestParamToDTO(OpenDoorDTO.class, request);
            String requestId = openDoorDTO.getRequestId();
            String robotId = openDoorDTO.getRobotId();
            String deviceUnique = openDoorDTO.getDeviceUnique();
            String effectiveTime = openDoorDTO.getEffectiveTime();
            String position = openDoorDTO.getPosition();
            String projectId = openDoorDTO.getProjectId();
            //打印入参
            LOG.info("【SDKV3 sendOpenDoor 入参】{}", openDoorDTO);
            //参数校验
            if (deviceUnique == null || deviceUnique.equals("")) {
                return new SDKMessageV3(SDKV3ErrorCodeEnum.NO_DEVICE_UNIQUE_ERROR.getErrorCode(), requestId);
            }
            //deviceUnique格式不对
            if (!DeviceUtil.isDeviceUnique(deviceUnique)) {
                return new SDKMessageV3(SDKV3ErrorCodeEnum.DEVICE_UNIQUE_ERROR.getErrorCode(), requestId);
            }
            //不允许给群控器发送开关门指令
            if (DeviceUtil.isYQK(deviceUnique)) {
                return new SDKMessageV3(SDKV3ErrorCodeEnum.OPEN_DOOR_FOR_YQK_ERROR.getErrorCode(), requestId);
            }
            if (effectiveTime == null || effectiveTime.equals("")) {
                return new SDKMessageV3(SDKV3ErrorCodeEnum.NO_EFFECTIVE_TIME_ERROR.getErrorCode(), requestId);
            }
            if (!MathUtil.isInteger(effectiveTime, 0, 99)) {
                return new SDKMessageV3(SDKV3ErrorCodeEnum.EFFECTIVE_TIME_ERROR.getErrorCode(), requestId);
            }
            int effectiveTimeInt = Integer.parseInt(effectiveTime);
            if (position == null || position.equals("")) {
                return new SDKMessageV3(SDKV3ErrorCodeEnum.NO_POSITION_ERROR.getErrorCode(), requestId);
            }
            if (!position.equals("in") && !position.equals("out")) {
                return new SDKMessageV3(SDKV3ErrorCodeEnum.POSITION_ERROR.getErrorCode(), requestId);
            }
            if (projectId == null || projectId.equals("")) {
                return new SDKMessageV3(SDKV3ErrorCodeEnum.PROJECT_ID_NOT_SET.getErrorCode(), requestId);
            }
            //数据设置
            openDoorDTO.setSnr(requestId + "-" + deviceUnique);
            openDoorDTO.setAppId(request.getAttribute("appId").toString());
            openDoorDTO.setAppSecret(request.getAttribute("appSecret").toString());
            openDoorDTO.setRobotDevelopDeviceType(RobotDevelopDeviceTypeConstant.YDT);
            openDoorDTO.setDeviceType(SolutionTypeConstant.STRING_ELEVATOR_ROBOT_CLOUD);
            //
            SDKMessageV3 response = iCheckService.check1(requestId, openDoorDTO.getAppId(), openDoorDTO.getRoleId());
            if (response.getMsgCode() != 0) {
                return response;
            }
            //
            Map<String, Object> AuthStatus = iOperateProjectServiceClient.getRobotGoProjectWhitelistAndDeviceAuthStatusByUserId(openDoorDTO.getProjectId(), openDoorDTO.getAppId());
            response = iCheckService.check2(requestId, requestTime, AuthStatus);
            if (response.getMsgCode() != 0) {
                return response;
            }
            //保存生成操作日志所需信息
            request.setAttribute("remark", openDoorDTO.toString());
            request.setAttribute("portType", LogDescConstant.SDK_CLOUD_ELEVATOR_TYPE_LOG_DESC);
            openDoorDTO.setRobotWhiteListAuthStatus(Integer.parseInt(AuthStatus.get("robotWhiteListAuthStatus") + ""));
            openDoorDTO.setRobotDeviceAuthStatus(Integer.parseInt(AuthStatus.get("robotDeviceAuthStatus") + ""));
            //设备权限以及机器人权限验证
            CloudDeviceSDKDTO t = new CloudDeviceSDKDTO();
            BeanUtils.copyProperties(openDoorDTO, t);
            Map<Object, Object> task = iTaskService.getTaskData(robotId);
            if (task == null) {
                LOG.error("【sdkv3 sendOpenDoorMethod 乘梯任务不存在】{} {} {} {} {}", robotId, deviceUnique, effectiveTimeInt, position, requestId);
                return new SDKMessageV3(SDKV3ErrorCodeEnum.TASK_NOT_EXIST.getErrorCode(), requestId);
            }
            if (task.get("controllerDeviceUnique").toString().equals("")) {
                t.setFlag(RobotDevelopDeviceTypeConstant.YDT);
                if (AuthStatus.get("robotToCloud").toString().equals("0")) {
                    return new SDKMessageV3(SDKV3ErrorCodeEnum.AUTH_YDT_ERROR.getErrorCode(), requestId);
                }
            } else {
                t.setFlag(RobotDevelopDeviceTypeConstant.YQK);
                if (AuthStatus.get("robotNoninductive").toString().equals("0")) {
                    return new SDKMessageV3(SDKV3ErrorCodeEnum.AUTH_YQK_ERROR.getErrorCode(), requestId);
                }
            }
            int result = this.checkDeveloperAuth(t);
            if (result == 1) {
                return new SDKMessageV3(SDKErrorCodeEnum.SDK_SERVER_NO_DEVICE_UNIQUE_ERR.getErrorCode(), requestId);
            } else if (result == 2) {
                return new SDKMessageV3(CloudElevarotErrorCodeEnum.ROBOT_AUTH_ERROR.getErrorCode(), requestId);
            }
            //云电梯设备判断,标准版不支持机器人功能
            DeviceElevatorInfoPO po = iCloudElevatorSDKServerCloudServiceClient.getElevatorByDeviceUnique(deviceUnique);
            if (po != null && po.getDeviceAttributes() != null && po.getDeviceAttributes() == 1) {
                return new SDKMessageV3(SDKErrorCodeEnum.SDK_DEVICE_NOT_SUPPORT_THIS_FUNCTIONS.getErrorCode(), requestId);
            }
            //检查参数
            OpenDoorCheckDTO openDoorCheckDTO = new OpenDoorCheckDTO();
            openDoorCheckDTO.setRequestId(requestId);
            openDoorCheckDTO.setRobotId(robotId);
            openDoorCheckDTO.setDeviceUnique(deviceUnique);
            openDoorCheckDTO.setUserId(openDoorDTO.getAppId());
            openDoorCheckDTO.setFlag(t.getFlag());
            response = iSDKV3EquipClient.openDoorCheck(openDoorCheckDTO);
            //有错误
            if (response.getMsgCode() != 0) {
                return response;
            }
            /*
                deviceId
            */
            HashMap<String, String> map = (HashMap<String, String>) response.getData();
            //机器人只能给自己已有任务关联的电梯发送开关门指令，且开门时机是可以进出电梯
            response = iTaskService.allowOpenDoor(robotId, deviceUnique, effectiveTimeInt, position, requestId);
            if (response.getMsgCode() != 0) {
                return response;
            }
            //
            String command = "";
            Robot robot = new Robot();
            robot.setRobotId(robotId);
            robot.setRobotPosition(position);
            //
            DoorCtrlCustomData doorCtrlCustomData = new DoorCtrlCustomData();
            doorCtrlCustomData.setRobot(robot);
            //关门
            if (effectiveTimeInt == 0) {
                DoorCtrlCloseParas doorCtrlCloseParas = new DoorCtrlCloseParas();
                doorCtrlCloseParas.setCmd("1033");
                doorCtrlCloseParas.setFOpenCtrl(effectiveTime);
                doorCtrlCloseParas.setSnr(requestId + "-" + deviceUnique);
                doorCtrlCloseParas.setSourceFrom("itlong");
                doorCtrlCloseParas.setCustomData(JSONObject.toJSONString(doorCtrlCustomData));
                doorCtrlCloseParas.setTimestamp(DateUtil.getTimestampString());
                //
                DoorCtrlClose doorCtrlClose = new DoorCtrlClose();
                doorCtrlClose.setCommand_name("doorCtrl");
                doorCtrlClose.setParas(doorCtrlCloseParas);
                doorCtrlClose.setService_id("SettingService");
                //
                DoorCtrlCloseWrap doorCtrlCloseWrap = new DoorCtrlCloseWrap();
                doorCtrlCloseWrap.setDoorCtrlClose(doorCtrlClose);
                doorCtrlCloseWrap.setRequestId(requestId);
                doorCtrlCloseWrap.setDeviceId(map.get("deviceId"));
                response = iSDKV3Client.closeDoor(doorCtrlCloseWrap);
                if (response.getMsgCode() != 0) {
                    return response;
                }
                //
                command = JSONObject.toJSONString(doorCtrlClose);
            } else {
                DoorCtrlOpenlParas doorCtrlOpenlParas = new DoorCtrlOpenlParas();
                doorCtrlOpenlParas.setCmd("1033");
                doorCtrlOpenlParas.setFOpenCtrl(effectiveTime);
                doorCtrlOpenlParas.setSnr(requestId + "-" + deviceUnique);
                doorCtrlOpenlParas.setSourceFrom("itlong");
                doorCtrlOpenlParas.setCustomData(JSONObject.toJSONString(doorCtrlCustomData));
                doorCtrlOpenlParas.setTimestamp(DateUtil.getTimestampString());
                //
                DoorCtrlOpen doorCtrlOpen = new DoorCtrlOpen();
                doorCtrlOpen.setCommand_name("doorCtrl");
                doorCtrlOpen.setParas(doorCtrlOpenlParas);
                doorCtrlOpen.setService_id("SettingService");
                //
                DoorCtrlOpenWrap doorCtrlOpenWrap = new DoorCtrlOpenWrap();
                doorCtrlOpenWrap.setDoorCtrlOpen(doorCtrlOpen);
                doorCtrlOpenWrap.setRequestId(requestId);
                doorCtrlOpenWrap.setDeviceId(map.get("deviceId"));
                //
                response = iSDKV3Client.openDoor(doorCtrlOpenWrap);
                if (response.getMsgCode() != 0) {
                    return response;
                }
                //
                command = JSONObject.toJSONString(doorCtrlOpen);
            }
            //设备删除的报文有可能非常及时，尝试做下面的逻辑，失败了不影响业务
            try {
                iTaskService.addTaskListItem(robotId, command);
                //指令通知到设备了才删除任务
                if (effectiveTimeInt == 0 && position.equals("out")) {
                    Map<Object, Object> taskData = iTaskService.getTaskData(robotId);
                    if (taskData != null && taskData.containsKey("step")) {
                        String step = taskData.get("step").toString();
                        if (step.equals(StepConstant.STRING_ARRIVE_START_FLOOR_ENTRY)) {
                            iTaskService.clearTask(TaskDeleteConstant.STEP_2, robotId, deviceUnique);
                        } else if (step.equals(StepConstant.STRING_ARRIVE_END_FLOOR_EXIT)) {
                            iTaskService.clearTask(TaskDeleteConstant.STEP_4, robotId, deviceUnique);
                        }
                    }
                }
            } catch (Exception e) {
                //不必关心错误
            }
            return new SDKMessageV3(BaseErrorCodeEnum.SUCCESS.getErrorCode(), requestId);
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("exception", e.toString());
            throw new DataAccessException("【SDKV3_云电梯_sendOpenDoor】发送开门关门指令失败", e);
        }
    }

    /**
     * <desc>
     * 任务信息
     * </desc>
     *
     * @return
     * @author zhouchun
     * @createDate 2021-05-18
     */
    @RequestMapping(path = "/getTaskInfo", method = RequestMethod.POST)
    @ResponseBody
    public Object getTaskInfo(HttpServletRequest request) {
        try {
            //收到请求的时间
            long requestTime = DateUtil.getTimestamp();
            TaskInfoDTO taskInfoDTO = HttpProtocolUtil.parseRequestParamToDTO(TaskInfoDTO.class, request);
            String requestId = taskInfoDTO.getRequestId();
            String robotId = taskInfoDTO.getRobotId();
            //打印入参
            LOG.info("【SDKV3 getTaskInfo 入参】{}", taskInfoDTO);
            if (!iTaskService.allowRequest(robotId)) {
                return new SDKMessageV3(SDKV3ErrorCodeEnum.API_LIMIT_ERROR.getErrorCode(), requestId);
            }
            //
            SDKMessageV3 response = iCheckService.check1(requestId, taskInfoDTO.getAppId(), taskInfoDTO.getRoleId());
            if (response.getMsgCode() != 0) {
                return response;
            }
            //
            if (!iTaskService.hasTaskKey(robotId)) {
                return new SDKMessageV3(BaseErrorCodeEnum.SUCCESS.getErrorCode(), requestId);
            }
            Map<Object, Object> map = iTaskService.getTaskData(robotId);
            if (map == null) {
                return new SDKMessageV3(BaseErrorCodeEnum.SUCCESS.getErrorCode(), requestId);
            }
            //如果没有派梯信息，尝试取消
            int step = Integer.parseInt(map.get("step").toString());
            if (step >= 2 && !map.get("controllerDeviceUnique").toString().equals("") && map.get("deviceUnique").toString().equals("")) {
                try {
                    CancelTravelWrap cancelTravelWrap = iTaskService.makeCancelTravelWrap(map.get("requestId").toString() + "-entry", map.get("iotDeviceId").toString(), robotId, requestId);
                    iSDKV3Client.submitCancelElevator(cancelTravelWrap);
                } catch (Exception e) {

                }
                return new SDKMessageV3(SDKV3ErrorCodeEnum.ENTRY_DEVICE_UNIQUE_ERROR.getErrorCode(), requestId);
            }
            //
            Task task = new Task();
            task.setRequestId(map.get("requestId").toString());
            task.setRobotId(robotId);
            task.setFromFloor(map.get("fromFloor").toString());
            task.setToFloor(map.get("toFloor").toString());
            task.setDeviceUnique(map.get("deviceUnique").toString());
            task.setEntryDeviceUnique(map.get("deviceUnique").toString());
            task.setStep(map.get("step").toString());
            task.setDoorOpenTime(map.get("doorOpenTime").toString());
            task.setDoorOpenTimeBaseTimestamp(map.get("doorOpenTimeBaseTimestamp").toString());
            task.setFloor(map.get("floor").toString());
            task.setFrontDoor(null);
            task.setMode(null);
            task.setUpDown(null);
            List<String> list = JSONObject.parseObject(map.get("list").toString(), List.class);
            task.setList(iTaskService.commandForApi(list));
            if (!map.get("controllerDeviceUnique").toString().equals("")) {
                task.setDeviceUnique(map.get("controllerDeviceUnique").toString());
            }
            return new SDKMessageV3(BaseErrorCodeEnum.SUCCESS.getErrorCode(), requestId, task);
        } catch (Exception e) {
            e.printStackTrace();
            throw new DataAccessException("【SDKV3_云电梯_getTaskInfo】获取任务信息失败", e);
        }
    }

    /**
     * <desc>
     * 开发者权限判断
     * <desc/>
     *
     * @param dto
     * @return
     * @author zhouchun
     * @createDate 2021-05-14
     */
    @UnAuthAccessRequired
    public int checkDeveloperAuth(CloudDeviceSDKDTO dto) throws Exception {
        if (dto.getFlag().equals(RobotDevelopDeviceTypeConstant.YQK)) {
            return controller(dto);
        }
        return elevator(dto);
    }

    private int elevator(CloudDeviceSDKDTO dto) throws Exception {
        CloudElevatorSDKGetByDeviceUniqueDTO cloudElevatorSDKGetByDeviceUniqueDTO = new CloudElevatorSDKGetByDeviceUniqueDTO();
        cloudElevatorSDKGetByDeviceUniqueDTO.setAppId(dto.getAppId());
        cloudElevatorSDKGetByDeviceUniqueDTO.setAppSecret(dto.getAppSecret());
        cloudElevatorSDKGetByDeviceUniqueDTO.setProjectId(dto.getProjectId());
        cloudElevatorSDKGetByDeviceUniqueDTO.setDeviceUnique(dto.getDeviceUnique());//云电梯
        cloudElevatorSDKGetByDeviceUniqueDTO.setRobotId(dto.getRobotWhiteListAuthStatus() == 0 ? "" : dto.getRobotId());

        CloudElevatorSDKServerElevatorKeyDTO cloudElevatorSDKServerElevatorKeyDTO = new CloudElevatorSDKServerElevatorKeyDTO();
        cloudElevatorSDKServerElevatorKeyDTO.setProjectId(cloudElevatorSDKGetByDeviceUniqueDTO.getProjectId());
        cloudElevatorSDKServerElevatorKeyDTO.setAppId(cloudElevatorSDKGetByDeviceUniqueDTO.getAppId());
        cloudElevatorSDKServerElevatorKeyDTO.setRoleId(dto.getRoleId());
        cloudElevatorSDKServerElevatorKeyDTO.setRobotId(cloudElevatorSDKGetByDeviceUniqueDTO.getRobotId());
        cloudElevatorSDKServerElevatorKeyDTO.setRobotWhiteListAuthStatus(dto.getRobotWhiteListAuthStatus());
        cloudElevatorSDKServerElevatorKeyDTO.setRobotDeviceAuthStatus(dto.getRobotDeviceAuthStatus());

        cloudElevatorSDKServerElevatorKeyDTO.setDeviceType(2);
        dto.setRobotDevelopDeviceType(2);
        List<String> deviceUniques = iCloudElevatorSDKRobotServiceClient.getElevatorKey(cloudElevatorSDKServerElevatorKeyDTO);
        LOG.info("【sdkv3权限检查 001】{} {} {}", dto, deviceUniques, cloudElevatorSDKGetByDeviceUniqueDTO.getDeviceUnique());
        if (deviceUniques == null || deviceUniques.isEmpty()) {
            return 1;
        } else {
            return 0;
        }
    }

    private int controller(CloudDeviceSDKDTO dto) throws Exception {
        CloudElevatorSDKGetByDeviceUniqueDTO cloudElevatorSDKGetByDeviceUniqueDTO = new CloudElevatorSDKGetByDeviceUniqueDTO();
        cloudElevatorSDKGetByDeviceUniqueDTO.setAppId(dto.getAppId());
        cloudElevatorSDKGetByDeviceUniqueDTO.setAppSecret(dto.getAppSecret());
        cloudElevatorSDKGetByDeviceUniqueDTO.setProjectId(dto.getProjectId());
        cloudElevatorSDKGetByDeviceUniqueDTO.setDeviceUnique(dto.getDeviceUnique());//群控器
        cloudElevatorSDKGetByDeviceUniqueDTO.setRobotId(dto.getRobotWhiteListAuthStatus() == 0 ? "" : dto.getRobotId());

        CloudElevatorSDKServerElevatorKeyDTO cloudElevatorSDKServerElevatorKeyDTO = new CloudElevatorSDKServerElevatorKeyDTO();
        cloudElevatorSDKServerElevatorKeyDTO.setProjectId(cloudElevatorSDKGetByDeviceUniqueDTO.getProjectId());
        cloudElevatorSDKServerElevatorKeyDTO.setAppId(cloudElevatorSDKGetByDeviceUniqueDTO.getAppId());
        cloudElevatorSDKServerElevatorKeyDTO.setRoleId(dto.getRoleId());
        cloudElevatorSDKServerElevatorKeyDTO.setRobotId(cloudElevatorSDKGetByDeviceUniqueDTO.getRobotId());
        cloudElevatorSDKServerElevatorKeyDTO.setRobotWhiteListAuthStatus(dto.getRobotWhiteListAuthStatus());
        cloudElevatorSDKServerElevatorKeyDTO.setRobotDeviceAuthStatus(dto.getRobotDeviceAuthStatus());
        cloudElevatorSDKServerElevatorKeyDTO.setDeviceType(1);
        dto.setRobotDevelopDeviceType(1);

        List<String> deviceUniques = iCloudElevatorSDKRobotServiceClient.getElevatorKey(cloudElevatorSDKServerElevatorKeyDTO);//返回云电梯
        LOG.info("【sdkv3权限检查 002】{} {} {}", dto, deviceUniques, cloudElevatorSDKGetByDeviceUniqueDTO.getDeviceUnique());
        if (deviceUniques == null || deviceUniques.isEmpty()) {
            return 1;
        } else {
            return 0;
        }
    }

}